const fs = require('fs');
const BASE_URL = './database'

/**
 * @description 创建文件夹
 * @param {String} fileName 
 * @param {Function} cb 
 */
const createFolder = (fileName, cb) => {
  fs.mkdir(`./${fileName}`, cb);
}

/**
 * @description 判断文件是否存在
 * @param {String} fileName 
 * @param {Function} cb 参数为Boolean，true:存在；false:不存在
 */
const folderExists = (fileName, cb) => {
	cb(fs.existsSync(fileName)) ;
}

/**
 * @description 创建文件
 * @param {String} fileName 
 * @param {Object | Array} content 
 * @param {Function} cb 
 */
const createFile = (fileName, content, cb) => {
  let file = JSON.stringify(content, null, '\t');
  fs.writeFile(`${BASE_URL}/${fileName}.json`, file, cb)
}

/**
 * @description 删除文件
 * @param {String} fileName 
 * @param {Function} cb 
 */
const deleteFile = (fileName, cb) => {
  fs.unlink(`${BASE_URL}/${fileName}.json`, cb)
}

/**
 * @description 读取文件
 * @param {String} fileName 
 * @param {Function} cb 
 */
const readFile = (fileName, cb) => {
  try {
    let data = fs.readFileSync(`${BASE_URL}/${fileName}.json`);
    cb(JSON.parse(data))
  } catch (err) {
    cb(err)
  }
}

/**
 * @description 写入文件
 * @param {String} fileName 
 * @param {Object | Array} newContent 
 * @param {Function} cb 
 */
const writeFile = (fileName, newContent, cb) => {
  let file = JSON.stringify(newContent, null, '\t');
  fs.writeFileSync(`${BASE_URL}/${fileName}.json`, file);
  cb()
}
exports.createFolder = createFolder;
exports.folderExists = folderExists;
exports.createFile = createFile;
exports.deleteFile = deleteFile;
exports.readFile = readFile;
exports.writeFile = writeFile;